// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const timeutil = require('./timeutil');
const ACTS = 'cloud-activities';
const GROUP = 'cloud-activities-groups';
const db = cloud.database();
const BASE = 'cloud-user-base';
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  /**获取OPENID并查询是否存在对应用户信息 */
  let openid = wxContext.OPENID;
  /**查询当前日期的活动 */
  let nowTime = timeutil.TimeCode();
  let activityRes = await db.collection(ACTS).where({
    startTime: _.lte(nowTime),
    endTime: _.gte(nowTime)
  }).get();
  /**获取符合日期条件全部活动列表 */
  let activities = activityRes.data;
  let nowActivity = {};
  if (activities.length == 0) {
    return {
      errCode: -1,
      errMsg: '当前日期暂无活动'
    }
  } else {
    /**选择第一个赋值 */
    nowActivity = activities[0];
  }
  let activityId = nowActivity._id;
  let groupRes = await db.collection(GROUP).where({
    activityId
  }).get();
  let groups = groupRes.data;
  if(groups.length == 0){
    return {
      errCode:-1,
      errMsg:'请在后台配置至少一个分组'
    }
  }
  /**获取数据库中已存在信息 */
  let baseRes = await db.collection(BASE).where({
    openid
  }).get();
  /**是否可以获取到基础信息？ */
  let selfInfo = {};
  if (baseRes.data.length != 0) {
    /**取第一个进行赋值操作 */
    selfInfo = baseRes.data[0];
  }
  /**获取分组信息 */

  return {
    selfInfo,
    groups
  };
}